import React, { useEffect } from 'react';
import { Spin, Space, Select, DatePicker, Row, Col } from 'antd';
import _ from 'lodash';
import moment from 'moment';

import { useTRState } from '#/utils/trHooks.jsx';
import { TjSegmented, TjChart } from '@/pages/ETrade/components';
import { getHistoryMarket } from './sercives';
import { getChartOption } from './helper';
import styles from './index.less';

const Son = ({ form, info, dayRange, hasSubRange = false, onChangeRange }) => {
  const monthDayTypeMap = {
    0: { title: '月每日', dateFmt: 'YYYY-MM', dateShowFmt: 'YYYYMM', picker: 'month' },
    1: { title: '日每时', dateFmt: 'YYYY-MM-DD', dateShowFmt: 'YYYYMMDD', picker: 'date' },
    2: { title: '时点统计', dateFmt: 'YYYY-MM-DD', dateShowFmt: 'YYYYMMDD', picker: 'range' },
    3: { title: '周每日', dateFmt: 'YYYY-w', dateShowFmt: 'YYYY-w', picker: 'week' },
  };
  const [state, setState] = useTRState({
    ...monthDayTypeMap[form.monthDayType],
    openDates: null,
    dateMo: null,
    params: null,
    loading: false,
    result: null,
  });

  useEffect(() => {
    initParams();
  }, [JSON.stringify(form), JSON.stringify(dayRange)]);

  const initParams = () => {
    if (!form || !dayRange?.length) return;
    let params = {
      monthDayType: form.monthDayType,
      mainFigureType: info.datakey, // 查询的主图类型，使用数据键
      dateType: form?.dateType,
      provinceId: form?.provinceId,
      stationId: form?.stationId,
      type: form?.type,
      marketId: form?.marketId,
    };
    if (form.monthDayType === 3) {
      // 接口参数设计有问题
      params.monthDayType = 0;
      params.week = true;
    }
    let dateMo;
    if (form.monthDayType === 2) {
      params.continuousOrAvg = false;
      dateMo = [moment(dayRange[0]), moment(dayRange[1])];
    } else {
      dateMo = moment(dayRange[0]);
    }
    state.params = params;
    setState({ params });
    changeDate(dateMo);
  };

  async function fetch(params) {
    setState({ params: { ...params }, loading: true });
    const res = await getHistoryMarket(params);
    const result = res?.dataMap?.[info.datakey] || null;
    setState({
      result,
      loading: false,
    });
  }

  function changeDate(v) {
    setState({ dateMo: v });
    if (form.monthDayType === 2) {
      if (!v?.length) return;
      state.params.startDate = v[0].format(state.dateFmt);
      state.params.endDate = v[1].format(state.dateFmt);
    } else {
      const { picker } = state;
      state.params.monthDay = v.format(state.dateFmt);
      if (hasSubRange) {
        // 周期相同取范围内最大最小，不同自取前后
        const sta = v.isSame(dayRange[0], picker)
          ? dayRange[0]
          : v.startOf(picker).format('YYYY-MM-DD');
        const end = v.isSame(dayRange[1], picker)
          ? dayRange[1]
          : v.endOf(picker).format('YYYY-MM-DD');
        onChangeRange?.([sta, end]);
      }
    }
    fetch(state.params);
  }

  function changeType(v) {
    state.params.continuousOrAvg = v;
    fetch(state.params);
  }

  const disabledDate = (v) => {
    // 限制可选范围
    if (!dayRange) return false;
    const tooEarly = v.startOf('day') < moment(dayRange[0]).startOf('day');
    const tooLate = v.startOf('day') > moment(dayRange[1]).startOf('day');
    return !!tooEarly || !!tooLate;
  };

  return (
    <Spin spinning={state.loading}>
      <div className={styles.chartHead}>
        <div className={styles.subTitle}>{state.title}</div>
        <Space size={16}>
          {/* 时点统计特殊处理 */}
          {state.picker === 'range' ? (
            <DatePicker.RangePicker
              value={state.openDates || state.dateMo}
              onChange={changeDate}
              style={{ width: 216 }}
              allowClear={false}
              disabledDate={disabledDate}
              format={state.dateShowFmt}
              getPopupContainer={(e) => e.parentNode}
              onCalendarChange={(openDates) => setState({ openDates })}
              onOpenChange={(open) => setState({ openDates: open ? [null, null] : null })}
            />
          ) : (
            <DatePicker
              value={state.dateMo}
              onChange={changeDate}
              style={{ width: 120 }}
              allowClear={false}
              disabledDate={disabledDate}
              format={state.dateShowFmt}
              getPopupContainer={(e) => e.parentNode}
              picker={state.picker}
            />
          )}
          {state.picker === 'range' && (
            <TjSegmented
              value={state.params?.continuousOrAvg}
              onChange={changeType}
              options={[
                { label: '连续', value: true },
                { label: '平均', value: false },
              ]}
            />
          )}
        </Space>
      </div>
      <TjChart option={getChartOption(state.result, info)} style={{ height: 300 }} />
    </Spin>
  );
};

export default ({ dayRange, form, info }) => {
  const [state, setState] = useTRState({
    mods: [],
    dayRangeSon: null, // 儿孙联动
  });

  useEffect(() => {
    initState();
  }, [form]);

  /**
   * 根据时间维度判断儿孙的标题、参数
   * dayMonthPoint: 0每日 1每月 2每时点 3每周
   * monthDayType: 0月每日 1日每时 2时点统计 3周每日
   */
  const initState = () => {
    const { dayMonthPoint, dateType } = form;
    let mods = [];
    if (dayMonthPoint === 0) {
      // 每日: {自定义:日每时、时点统计, 固定:日每时}
      mods = dateType === 0 ? [1, 2] : [1];
    } else if (dayMonthPoint === 1) {
      // 每月: 月每日、日每时
      mods = [0, 1];
    } else if (dayMonthPoint === 3) {
      // 每月: 周每日、日每时
      mods = [3, 1];
    }
    setState({ mods });
  };

  return !state.mods.length ? null : (
    <Row gutter={[24, 0]}>
      {/* 一级下钻 */}
      <Col span={state.mods.length === 1 ? 24 : 12}>
        <Son
          dayRange={dayRange}
          info={info}
          form={{
            ...form,
            monthDayType: state.mods[0],
          }}
          hasSubRange={state.mods[1] === 1}
          onChangeRange={(v) => setState({ dayRangeSon: v })}
        />
      </Col>
      {/* 二级下钻 */}
      {state.mods.length === 2 && (
        <Col span={12}>
          <Son
            dayRange={state.mods[1] === 1 ? state.dayRangeSon : dayRange}
            info={info}
            form={{
              ...form,
              monthDayType: state.mods[1],
            }}
          />
        </Col>
      )}
    </Row>
  );
};
